<template>
  <div class="container">
    <el-dialog
      :title="title"
      :visible.sync="dialogVisible"
      :close-on-click-modal="false"
      :show-close="false"
    >
      <el-form
        :model="form"
        :label-width="formLabelWidth"
        :rules="rules"
        v-loading="loading"
        ref="ruleForm"
      >
        <el-form-item label="用户名称" prop="username">
          <el-input v-model="form.username" auto-complete="false"></el-input>
        </el-form-item>
        <el-form-item label="员工编号" prop="employeeId">
          <el-input v-model="form.employeeId"></el-input>
        </el-form-item>
        <el-form-item label="邮箱账号" prop="mail">
          <el-input v-model="form.mail"></el-input>
        </el-form-item>
        <el-form-item label="账号密码" prop="password">
          <el-input v-model="form.password"></el-input>
        </el-form-item>
        <el-form-item label="科室名称" prop="office">
          <el-select
            v-model="form.office"
            placeholder="请选择科室"
            @change="change"
          >
            <el-option
              v-for="(item, index) in offices"
              :key="item.id + index"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="用户角色" prop="userRoles">
          <el-select
            v-model="form.userRoles"
            :disabled="handleDisabled()"
            multiple
            value-key="id"
            @change="change"
            placeholder="请选择角色"
          >
            <el-option
              v-for="(item, index) in rolesDataList"
              :key="item.id + index"
              :label="item.name"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="账号状态" prop="enabled" v-if="type == 'edit'">
          <el-select
            v-model="form.enabled"
            placeholder="请选择状态"
            :disabled="handleDisabled()"
          >
            <el-option
              v-for="item in userStates"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="close">取消</el-button>
        <el-button @click="submit">确定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import store from "../../store";
import { postRequest } from "@/api/api";
import { getRequest } from "@/api/api";
export default {
  name: "UserEdit",
  props: {
    userId: {
      default: -1,
    },
    userData: {
      default: {},
    },
    type: {
      default: "create",
      type: String,
    },
    dialogVisible: {
      default: false,
      type: Boolean,
    },
    title: {
      default: "用户管理",
      type: String,
    },
  },
  data() {
    return {
      loading: false,
      disabled: true,
      loginUserId: store.getters.loginUser.data.id,
      formLabelWidth: "180",
      labelPosition: "right",
      form: {
        username: "",
        mail: "",
        employeeId: "",
        office: 1,
        userRoles: [],
        enabled: 1,
        password: "123456",
      },
      rolesDataList: store.getters.rolesDataList,
      offices: store.getters.offices,
      userStates: [
        {
          value: true,
          label: "启用",
        },
        {
          value: false,
          label: "停用",
        },
      ],

      rules: {
        username: [
          { required: true, message: "请输入员工名称", trigger: "blur" },
          { min: 2, max: 10, message: "长度在2到10个字符", trigger: "blur" },
        ],
        employeeId: [
          { required: true, message: "请输入员工工号", trigger: "blur" },
        ],
        mail: [
          { required: true, message: "请输入员工邮箱号", trigger: "blur" },
        ],
        office: [
          {
            required: true,
            validator: function (rule, value, callback) {
              if (!value) {
                callback(new Error("请选择科室"));
              } else {
                callback();
              }
            },
          },
        ],
        userRoles: [
          {
            required: true,
            validator: function (rule, value, callback) {
              if (value.length === 0) {
                callback(new Error("请选择角色"));
              } else {
                callback();
              }
            },
          },
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          { min: 6, message: "长度在6个字符以上", trigger: "blur" },
        ],
        enabled: [
          { required: true, message: "请选择账户状态", trigger: "change" },
        ],
      },
    };
  },
  watch: {
    dialogVisible: {
      handler(newVal, oldVal) {
        if (this.type != "create" && newVal == true) {
          this.loading = true;
          console.log(this.userId);
          console.log("userdata", this.userData);
          let path = "/user/" + this.userId;
          getRequest(path)
            .then((res) => {
              // this.form = res.data.data;
              Object.assign(this.form, res.data.data);
              this.form.office = parseInt(this.form.office);
              console.log("form", this.form);
              let roles = this.form.roles;
              this.form.userRoles = [];
              for (let i = 0; i < roles.length; i++) {
                this.form.userRoles.push(roles[i].id);
              }
              // let reg = /,$/gi;
              // this.form.roles=this.form.roles.replace(reg,"");
              // this.form.roles = ["超级管理员", "普通用户"]
              console.log(this.form.userRoles);
              this.loading = false;
            })
            .catch((err) => {
              this.$message.error(err);
            });
        } else {
          this.form = {
            username: "",
            mail: "",
            employeeId: "",
            userRoles: [4],
            enabled: 1,
            office: 18,
            password: "123456",
          };
          this.loading = false;
        }
      },
      immediate: true,
    },
  },
  methods: {
    close() {
      // this.resetForm("ruleForm");
      this.$refs["ruleForm"].clearValidate();
      this.form = {
        username: "",
        mail: "",
        employeeId: "",
        office: 1,
        userRoles: [],
        enabled: 1,
        password: "123456",
      };
      this.$emit("closeDialog");
    },
    change(val) {
      this.$forceUpdate();
      console.log(val);
      console.log("roles", this.form.userRoles);
    },
    handleDisabled() {
      if (this.userId == this.loginUserId) {
        return true;
      } else {
        return false;
      }
    },
    submit() {
      this.$refs["ruleForm"].validate((valid) => {
        if (valid) {
          // this.close();
          let data = this.form;
          // this.$refs["ruleForm"].clearValidate();
          this.$emit("submit", data);
        } else {
          this.$message.error("校验未通过，请检查必填项");
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
  },
};
</script>  

<style scoped>
.el-input {
  width: auto;
}
.container /deep/ .el-input__inner {
  width: 400px;
}
</style>